package de.tudarmstadt.ukp.muip.fibqdojo.io.raw;

import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.StartElement;

import de.tudarmstadt.ukp.muip.fibqdojo.interfaces.IFIBQToken;
import de.tudarmstadt.ukp.muip.fibqdojo.visitor.GetFormVisitor;
import de.tudarmstadt.ukp.muip.fibqdojo.visitor.GetLemmaVisitor;
import de.tudarmstadt.ukp.muip.fibqdojo.visitor.GetPartOfSpeechVisitor;

public class TokenWriter extends AbstractTokenWriter {

    public TokenWriter(XMLEventFactory eventFactory, XMLEventWriter eventWriter) {
        super(eventFactory, eventWriter);
    }

    public void processToken(IFIBQToken token) throws XMLStreamException {
        addNode(FORM, getForm(token));
        addNode(POS, getPos(token));
        addNode(LEMMA, getLemma(token));
    }

    private String getPos(IFIBQToken token) {
        GetPartOfSpeechVisitor visitor = new GetPartOfSpeechVisitor();
        token.accept(visitor);
        return visitor.getPartOfSpeech();
    }

    private String getLemma(IFIBQToken token) {
        GetLemmaVisitor visitor = new GetLemmaVisitor();
        token.accept(visitor);
        return visitor.getLemma();
    }

    private void addNode(String name, String value) throws XMLStreamException {
        if (value.equals("")) {
            return;
        }
        StartElement sentStartElement = eventFactory.createStartElement("", "", name);
        eventWriter.add(sentStartElement);
        Characters characters = eventFactory.createCharacters(value);
        eventWriter.add(characters);
        eventWriter.add(eventFactory.createEndElement("", "", name));
    }

    private String getForm(IFIBQToken token) {
        GetFormVisitor visitor = new GetFormVisitor();
        token.accept(visitor);
        return visitor.getForm();
    }

}
